package cn.kingshion.juc.locks;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 用于解决多线程安全问题的方式：
 * 1. 同步代码块
 * 2. 同步方法
 * 3. 同步锁 Lock（jdk 1.5 以后）
 * - 是一个显示锁，需要通过 lock() 方法上锁，使用 unlock() 方法进行释放锁；
 */
public class LockTest {

    public static void main(String[] args) {
        Ticks tickets = new Ticks();
        new Thread(tickets,"A").start();
        new Thread(tickets,"B").start();
        new Thread(tickets,"C").start();
    }

}

class Ticks implements Runnable {

    private int ticks = 100;
    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            lock.lock();
            try {
                if (ticks > 0) {
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                    }
                    System.out.println(Thread.currentThread().getName() + "卖出了第" + ticks + "张票,还剩" + (--ticks) + "张票");
                }
            } finally {
                lock.unlock();
            }
        }
    }
}
